1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/*!
Lambda functions
*/
use super::*;

/// A lambda function
#[derive(Debug, Clone)]
pub struct Lambda {
    /// The type of this lambda function's parameter, if annotated
    param_ty: Option<TermId>,
    /// The result of this lambda function
    result: TermId,
    /// The type annotation of this lambda function
    annot: Option<Annotation>,
    /// The code of this lambda function
    code: Code,
    /// The filter of this lambda function
    filter: VarFilter,
    /// The pre-computed flags of this lambda function
    flags: AtomicTyckFlags,
    /// The form of this lambda function
    form: Form,
}

impl Lambda {
    /// Create a new lambda function without any type-checking
    pub fn new_unchecked(
        param_ty: Option<TermId>,
        result: TermId,
        annot: Option<Annotation>,
    ) -> Lambda {
        let code = Self::compute_code(param_ty.as_ref(), &result, annot.as_ref());
        let filter = Self::compute_filter(param_ty.as_ref(), &result, annot.as_ref());
        let flags = Self::compute_flags(param_ty.as_ref(), &result, annot.as_ref()).into();
        let form = Self::compute_form(param_ty.as_ref(), &result, annot.as_ref());
        Lambda {
            param_ty,
            result,
            annot,
            code,
            filter,
            flags,
            form,
        }
    }

    /// Create a new dependent function type which automatically has the minimal dependent function type
    pub fn new_direct(
        param_ty: Option<TermId>,
        result: TermId,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Lambda {
        let ty = if let Some(param_ty) = &param_ty {
            Self::compute_ty(param_ty, &result, ctx).ok()
        } else {
            None
        };
        let annot = if let Some(ty) = ty {
            Some(Annotation::from_ty(ty.into_id_with(ctx)).expect("Pi types are always types"))
        } else {
            None
        };
        let typed = annot.is_some();
        let result = Self::new_unchecked(param_ty, result, annot);
        result.flags.set_flag(LocalTyck, typed.into());
        result
    }

    /// Create a new dependent function type which automatically has the minimal dependent function type
    ///
    /// Will return an error on an obviously mistyped term, but results are not necessarily type-checked
    pub fn new_typed(
        param_ty: TermId,
        result: TermId,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Lambda, Error> {
        let direct = Self::new_direct(Some(param_ty), result, ctx.cons_ctx());
        if direct.annot.is_none() {
            //TODO: fix error...
            return Err(Error::NotImplemented);
        } else if ty.is_none() {
            //TODO: think about this...
            Ok(direct)
        } else {
            direct.coerced(ty, ctx)
        }
    }

    /// Compute the form of a lambda function
    #[inline]
    pub fn compute_form(
        _param_ty: Option<&TermId>,
        result: &TermId,
        _annot: Option<&Annotation>,
    ) -> Form {
        result.form().join(if Self::result_is_eta_normal(result) {
            Form::HeadEta
        } else {
            Form::Head
        })
    }

    /// Compute the code for a lambda function with the given parameter type, result, and type annotation
    pub fn compute_code(
        param_ty: Option<&TermId>,
        result: &TermId,
        ty: Option<&Annotation>,
    ) -> Code {
        let mut hasher = AHasher::new_with_keys(0x653, 0x5833);
        let result_code = result.code();
        result_code.pure().hash(&mut hasher);
        let pre = hasher.finish();
        param_ty.hash(&mut hasher);
        ty.hash(&mut hasher);
        let post = hasher.finish();
        Code::new(pre, post)
    }

    /// Compute the filter for a lambda function with the given parameter type, result, and type annotation
    pub fn compute_filter(
        param_ty: Option<&TermId>,
        result: &TermId,
        ty: Option<&Annotation>,
    ) -> VarFilter {
        result
            .get_filter()
            .shift_down_value(result)
            .union(param_ty.get_filter())
            .union(ty.get_filter())
    }

    /// Compute the flags for a lambda function with the given parameter type, result, and type annotation
    pub fn compute_flags(
        param_ty: Option<&TermId>,
        result: &TermId,
        ty: Option<&Annotation>,
    ) -> TyckFlags {
        let maybe_tyck =
            L4::with_false(!ty.maybe_tyck() || !param_ty.maybe_tyck() || !result.maybe_tyck());
        TyckFlags::default().with_flag(TyckFlag::GlobalTyck, maybe_tyck)
    }

    /// Construct the identity type for a given parameter type in a given context
    pub fn id_with(
        param_ty: Option<TermId>,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Lambda, Error> {
        let (var_ty, ty) = if let Some(param_ty) = &param_ty {
            let var_ty = param_ty.shifted_id(1, 0, ctx)?;
            let ty = Pi::new(param_ty.clone(), var_ty.clone(), ctx).into_id_with(ctx);
            debug_assert_eq!(Pi::unary_with(param_ty.clone(), ctx)?, ty);
            (Some(var_ty), Some(ty))
        } else {
            (None, None)
        };
        let result = Var::new_unchecked(0, var_ty).into_id_with(ctx);
        Ok(Lambda::new_unchecked(
            param_ty,
            result,
            ty.and_then(|ty| Annotation::from_ty(ty).ok()),
        ))
    }

    /// Compute whether a lambda function locally type-checks
    pub fn compute_local_tyck(param_ty: &TermId, result: &TermId, annot: AnnotationRef) -> bool {
        if let Term::Pi(base) = &*annot.base() {
            Self::compute_local_tyck_pi(param_ty, result, base)
        } else {
            false
        }
    }

    /// Compute whether a lambda function locally type-checks given a pi type
    pub fn compute_local_tyck_pi(param_ty: &TermId, result: &TermId, base: &Pi) -> bool {
        param_ty
            .eq_in(base.param_ty(), &mut Structural)
            .unwrap_or(false)
            && if let Some(annot) = result.annot() {
                annot
                    .ty()
                    .eq_term_in(base.result(), &mut Structural)
                    .unwrap_or(false)
            } else {
                false
            }
    }

    /// Compute the type of a lambda function
    pub fn compute_ty(
        param_ty: &TermId,
        result: &TermId,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Pi, Error> {
        let result_ty = result.ty_id(ctx).ok_or(Error::ExpectedAnnot)?;
        Ok(Pi::new(param_ty.clone(), result_ty.into_owned(), ctx))
    }

    /// Get the parameter type of this lambda function
    pub fn param_ty(&self) -> Option<&TermId> {
        self.param_ty.as_ref()
    }

    /// Get the result of this lambda function
    pub fn result(&self) -> &TermId {
        &self.result
    }

    /// Get whether a lambda function result is in eta-normal form
    pub fn result_is_eta_normal(result: &TermId) -> bool {
        if let Term::App(result) = &**result {
            if let Term::Var(right) = &**result.right() {
                if right.ix() == 0 {
                    return result.left().has_var_dep(0, false);
                }
            }
        }
        true
    }

    /// Get whether this lambda function is in eta-normal form
    pub fn is_eta_normal(&self) -> bool {
        if self.form().is_enf() {
            true
        } else {
            Self::result_is_eta_normal(&self.result)
        }
    }

    /// Eta reduce this lambda function. Return `None` if in eta-normal form
    pub fn eta(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<TermId> {
        if self.form().is_enf() {
            return None;
        }
        if let Term::App(result) = &*self.result {
            if let Term::Var(right) = &**result.right() {
                if right.ix() == 0 {
                    return Some(
                        result
                            .left()
                            .shift(-1, 0, ctx.cons_ctx())
                            .ok()?
                            .unwrap_or_else(|| result.left().clone_into_id_with(ctx.cons_ctx())),
                    );
                }
            }
        }
        None
    }
}

impl Eq for Lambda {}

impl PartialEq for Lambda {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.eq_in(other, &mut Structural).unwrap_or(false)
    }
}

impl Hash for Lambda {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.result.hash(state);
        self.param_ty.hash(state);
        self.annot.hash(state);
    }
}

impl Cons for Lambda {
    type Consed = Lambda;

    #[inline]
    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed> {
        let result = self.result.cons_id(ctx);
        let param_ty = self.param_ty.cons(ctx).flatten();
        let ty = self.annot.cons(ctx).flatten();
        if result.is_none() && param_ty.is_none() && ty.is_none() {
            return None;
        }
        let result = Lambda {
            param_ty: param_ty.or_else(|| self.param_ty.clone()),
            result: result.unwrap_or_else(|| self.result.clone()),
            annot: ty.or_else(|| self.annot.clone()),
            code: self.code,
            filter: self.filter,
            flags: self.flags.clone(),
            form: self.form,
        };
        Some(result)
    }

    #[inline]
    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for Lambda {
    type Substituted = Lambda;

    fn subst_rec(&self, ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<Lambda>, Error> {
        if !ctx.intersects(self.filter, self.code, self.form) {
            return Ok(None);
        }
        let param_ty = ctx.push_param(self.param_ty.as_ref())?;
        let result = self.result.subst_id(ctx);
        ctx.pop_param()?;
        let result = result?;
        if param_ty.is_none() && result.is_none() {
            return Ok(None);
        }
        let ty = self.annot.subst_rec(ctx)?;
        let param_ty = param_ty.or_else(|| self.param_ty.consed(ctx.cons_ctx()));
        let result = result.unwrap_or_else(|| self.result.consed(ctx.cons_ctx()));
        let annot = ty.unwrap_or_else(|| self.annot.consed(ctx.cons_ctx()));
        let filter = Self::compute_filter(param_ty.as_ref(), &result, annot.as_ref());
        let code = Self::compute_code(param_ty.as_ref(), &result, annot.as_ref());
        //TODO: term flag optimization
        let flags = Self::compute_flags(param_ty.as_ref(), &result, annot.as_ref()).into();
        let form = Self::compute_form(param_ty.as_ref(), &result, annot.as_ref());
        let term = Lambda {
            param_ty,
            result,
            annot,
            filter,
            flags,
            code,
            form,
        };
        Ok(Some(term))
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl Typecheck for Lambda {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        if let (Some(annot), Some(param_ty)) = (&self.annot, &self.param_ty) {
            Self::compute_local_tyck(param_ty, &self.result, annot.borrow_annot())
        } else {
            false
        }
    }

    fn do_global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        // Type-check parameter type
        if !self.param_ty.tyck(ctx)? {
            return Some(false);
        }

        // Constrain parameter type
        ctx.push_param(self.param_ty.as_ref()).ok()?;

        // Type-check result
        let result_tyck = self.result.tyck(ctx);

        // Reset context
        ctx.pop_param().ok()?;

        result_tyck
    }

    #[inline]
    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.annot.tyck(ctx)
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        self.flags.load_flags()
    }

    #[inline]
    fn set_flags(&self, flags: TyckFlags) {
        self.flags.set_flags(flags);
    }
}

impl HasDependencies for Lambda {
    #[inline]
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        if !self.filter.contains(ix) {
            false
        } else if self.filter.exact() {
            true
        } else if self.param_ty.has_var_dep(ix, equiv) {
            true
        } else if self.result.has_var_dep(ix + 1, equiv) {
            true
        } else if self.annot.has_var_dep(ix, equiv) {
            true
        } else {
            false
        }
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.filter
    }

    #[inline]
    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        if let Some(contains) = self.filter.contains_below(ix, base) {
            contains
        } else {
            self.param_ty.has_dep_below(ix, base)
                || self.result.has_dep_below(ix + 1, base + 1)
                || self.annot.has_dep_below(ix, base)
        }
    }
}

impl TermEq for Lambda {
    #[inline]
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        if let Some(result) =
            ctx.approx_term_eq_code((self.code, self.form), (other.code, other.form))
        {
            return result;
        }
        let annot = if ctx.cmp_annot() {
            self.annot.eq_in(&other.annot, ctx)
        } else if ctx.cmp_var() {
            Some(self.annot.is_some() == other.annot.is_some())
        } else {
            Some(true)
        };
        if let Some(false) = annot {
            return Some(false);
        }
        let param_ty = if ctx.cmp_param() {
            self.param_ty.eq_in(&other.param_ty, ctx)
        } else if ctx.cmp_var() {
            Some(self.annot.is_some() == other.annot.is_some())
        } else {
            Some(true)
        };
        if let Some(false) = param_ty {
            return Some(false);
        }
        let result = self.result.eq_in(&other.result, ctx);
        if let Some(false) = result {
            return Some(false);
        }
        Some(annot? && param_ty? && result?)
    }
}

impl Value for Lambda {
    type ValueConsed = Lambda;
    type ValueSubstituted = Lambda;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Lambda(self)
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        self.annot.as_ref().map(Annotation::borrow_annot)
    }

    #[inline]
    fn id(&self) -> Option<NodeIx> {
        None
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        todo!()
    }

    #[inline]
    fn is_root(&self) -> bool {
        true
    }

    #[inline]
    fn coerce(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Lambda>, Error> {
        if let Some(annot) = &self.annot {
            //TODO: deal with locally-bad annotations?
            if let Some(ty) = ty {
                if let Some(annot) = annot.coerce_ty(&ty, ctx)? {
                    return self.annotate_unchecked(annot, ctx.cons_ctx());
                }
            }
            Ok(None)
        } else {
            //TODO: review
            let (param_ty, result) = if let Some(param_ty) = &self.param_ty {
                let param_ty = param_ty.coerced(None, ctx)?;
                ctx.push_param(Some(&param_ty))?;
                let result = self.result.coerced(None, ctx);
                ctx.pop_param()?;
                (param_ty, result?)
            } else {
                ctx.push_param(None)?;
                let result = self.result.coerced(None, ctx);
                let param_ty = ctx.infer(0).ok_or(Error::CannotInfer);
                ctx.pop_param()?;
                (param_ty?, result?)
            };
            let func = Lambda::new_typed(param_ty, result, None, ctx)?;
            debug_assert_eq!(func.cons(ctx.cons_ctx()), None);
            Ok(Some(func))
        }
    }

    fn annotate_unchecked(
        &self,
        annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<Lambda>, Error> {
        if let Some(curr_annot) = &self.annot {
            if curr_annot.is_sub_annot(&annot) {
                return Ok(None);
            }
        }
        Ok(Some(Lambda::new_unchecked(
            self.param_ty.clone(),
            self.result.clone(),
            Some(annot),
        )))
    }

    #[inline]
    fn is_subtype_in(
        &self,
        _other: &Term,
        _ctx: &mut (impl TermEqCtxMut + ?Sized),
    ) -> Option<bool> {
        // Lambda functions are never types
        Some(false)
    }

    #[inline]
    fn universe(&self) -> Option<Universe> {
        None
    }

    #[inline]
    fn code(&self) -> Code {
        self.code
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        Self::compute_code(None, &self.result, None)
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        match other {
            Term::Lambda(other) => self.eq_in(other, ctx),
            _ if other.is_root() => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn apply(
        &self,
        args: &mut SmallVec<[TermId; 2]>,
        ctx: &mut (impl EvalCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        if let Some(param) = args.pop() {
            ctx.push_subst(param)?;
            let result = self.result.apply(args, ctx);
            ctx.pop_subst()?;
            Ok(Some(
                result?.unwrap_or_else(|| self.result.consed(ctx.cons_ctx())),
            ))
        } else {
            self.subst_id(ctx)
        }
    }

    #[inline]
    fn form(&self) -> Form {
        self.form
    }
}

impl PartialEq<Term> for Lambda {
    fn eq(&self, other: &Term) -> bool {
        match other {
            Term::Lambda(other) => self.eq(other),
            _ => false,
        }
    }
}

impl PartialEq<TermId> for Lambda {
    fn eq(&self, other: &TermId) -> bool {
        self.eq(&**other)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use smallvec::smallvec;

    #[test]
    fn basic_identity_set_test() {
        let mut ctx = DisjointSetCtx::default();
        let set = Universe::set().into_id_with(&mut ctx);
        assert_eq!(set.tyck(&mut ctx), Some(true));
        assert_eq!(set.tyck_var(&mut ctx), Some(true));
        let a = Var::new_unchecked(5, Some(set)).into_id_with(&mut ctx);
        assert_eq!(a.tyck(&mut ctx), Some(true));
        assert_eq!(a.tyck_var(&mut ctx), Some(true));
        let id = Lambda::id_with(Some(a.clone()), &mut ctx)
            .unwrap()
            .into_id_with(&mut ctx);
        assert_eq!(id.tyck(&mut ctx), Some(true));

        assert_eq!(id.tyck_var(&mut ctx), Some(true));
        let raw_id = Lambda::id_with(None, &mut ctx)
            .unwrap()
            .into_id_with(&mut ctx);
        assert_eq!(raw_id.tyck(&mut ctx), Some(false));
        assert_eq!(raw_id.tyck_var(&mut ctx), Some(false));
        assert_ne!(id, raw_id);
        assert_ne!(id.code(), raw_id.code());
        assert_eq!(id.code().pure(), raw_id.code().pure());
        assert_eq!(id.untyped_code(), raw_id.code());
        assert_eq!(raw_id.untyped_code(), raw_id.code());

        let x = Var::new_unchecked(3, Some(a.clone())).into_id_with(&mut ctx);
        assert_eq!(x.tyck_var(&mut ctx), Some(true));
        let id_x = App::new(id.clone(), x.clone(), &mut ctx);
        assert!(id_x.local_tyck(&mut ctx));
        assert_eq!(id_x.tyck(&mut ctx), Some(true));
        assert_eq!(id_x.tyck_var(&mut ctx), Some(true));
        assert_eq!(id_x.form(), Form::Eta);

        assert_eq!(
            id_x,
            App::new_unchecked(id.clone(), x.clone(), Annotation::from_ty(a.clone()).ok())
        );
        assert_eq!(
            id_x.normalized(Form::BetaEta, u64::MAX, &mut Trivial::default())
                .unwrap(),
            x
        );
        assert_eq!(
            id_x.normalized(Form::Beta, u64::MAX, &mut Trivial::default())
                .unwrap(),
            x
        );
        assert_eq!(
            id_x.normalized(Form::Head, u64::MAX, &mut Trivial::default())
                .unwrap(),
            x
        );
        assert_eq!(
            id_x.normalize(Form::Null, u64::MAX, &mut Trivial::default())
                .unwrap(),
            None
        );
    }

    #[test]
    fn basic_identity_bool_test() {
        let mut ctx = DisjointSetCtx::default();
        let b = BOOL.clone();
        assert_eq!(b.tyck(&mut ctx), Some(true));
        assert_eq!(b.tyck_var(&mut ctx), Some(true));
        let id = Lambda::id_with(Some(b.clone()), &mut ctx)
            .unwrap()
            .into_id_with(&mut ctx);
        assert_eq!(id.tyck(&mut ctx), Some(true));
        assert_eq!(id.tyck_var(&mut ctx), Some(true));
        assert_eq!(id.form(), Form::BetaEta);
        assert!(id.is_hnf());
        assert!(id.is_bnf());
        let raw_id = Lambda::id_with(None, &mut ctx)
            .unwrap()
            .into_id_with(&mut ctx);
        assert_eq!(raw_id.tyck(&mut ctx), Some(false));
        assert_eq!(raw_id.tyck_var(&mut ctx), Some(false));
        assert_eq!(raw_id.form(), Form::BetaEta);
        assert!(raw_id.is_hnf());
        assert!(raw_id.is_bnf());
        assert_ne!(id, raw_id);
        assert_ne!(id.code(), raw_id.code());
        assert_eq!(id.code().pure(), raw_id.code().pure());
        assert_eq!(id.untyped_code(), raw_id.code());
        assert_eq!(raw_id.untyped_code(), raw_id.code());

        let t = TRUE.clone();
        let f = FALSE.clone();
        assert_eq!(
            id.apply(&mut smallvec![t.clone()], &mut SubstVec::new(TRIVIAL))
                .unwrap()
                .unwrap(),
            t
        );
        assert_eq!(
            id.apply(&mut smallvec![f.clone()], &mut SubstVec::new(TRIVIAL))
                .unwrap()
                .unwrap(),
            f
        );
    }

    #[test]
    fn lambda_param_ty_mismatch() {
        let mut ctx = DisjointSetCtx::default();
        let b = BOOL.clone();
        let set = Universe::set().into_id_with(&mut ctx);
        let xb = Var::with_ty(0, b.clone()).into_id_with(&mut ctx);
        assert_eq!(xb.tyck(&mut ctx), Some(true));
        let set_bool = Pi::new(set.clone(), b.clone(), &mut ctx).into_id_with(&mut ctx);
        assert_eq!(set_bool.tyck_var(&mut ctx), Some(true));
        let lambda =
            Lambda::new_unchecked(Some(set), xb, Annotation::from_ty(set_bool.clone()).ok());
        assert_eq!(lambda.ty().as_deref(), Some(&*set_bool));
        assert_eq!(lambda.base().as_deref(), Some(&*set_bool));
        assert_eq!(lambda.tyck(&mut ctx), Some(true));
        assert_eq!(lambda.tyck_var(&mut ctx), Some(false));
    }

    #[test]
    fn lambda_bool_return_inference() {
        let mut ctx = DisjointSetCtx::default();
        let f_untyped = Lambda::new_unchecked(Some(BOOL.clone()), FALSE.clone(), None);
        let f_typed = Lambda::new_direct(Some(BOOL.clone()), FALSE.clone(), &mut ctx);
        assert_ne!(f_untyped, f_typed);
        assert_eq!(f_untyped.coerce(None, &mut ctx).unwrap().unwrap(), f_typed);
        assert_eq!(f_typed.coerce(None, &mut ctx), Ok(None));
        let id_var_untyped = Lambda::new_unchecked(
            Some(BOOL.clone()),
            Var::with_ix(0).into_id_with(&mut ctx),
            None,
        );
        let id_untyped = Lambda::new_unchecked(
            Some(BOOL.clone()),
            Var::with_ty(0, BOOL.clone()).into_id_with(&mut ctx),
            None,
        );
        let id = Lambda::id_with(Some(BOOL.clone()), &mut ctx).unwrap();
        assert_ne!(id_var_untyped, id);
        assert_eq!(
            id_var_untyped.coerce(None, &mut ctx),
            Err(Error::InferenceFailure)
        );
        assert_eq!(
            id_var_untyped
                .coerce(None, &mut MapTyCtx::new(&mut ctx))
                .unwrap()
                .unwrap(),
            id
        );
        assert_eq!(id_untyped.coerce(None, &mut ctx).unwrap().unwrap(), id);
        assert_eq!(id.coerce(None, &mut ctx), Ok(None));
    }

    #[test]
    fn lambda_subst() {
        let mut ctx = SubstVec::new(StandardCtx::default());
        ctx.push_subst(TRUE.clone()).unwrap();
        let c1 = Lambda::new_direct(
            Some(BOOL.clone()),
            Var::with_ty(1, BOOL.clone()).into_id_with(ctx.cons_ctx()),
            ctx.cons_ctx(),
        )
        .into_id_with(ctx.cons_ctx());
        let ct = Lambda::new_direct(Some(BOOL.clone()), TRUE.clone(), ctx.cons_ctx())
            .into_id_with(ctx.cons_ctx());
        assert_eq!(c1.subst_id(&mut ctx).unwrap().unwrap(), ct);
    }
}